package io.plus.interactive.collections;

import drds.common.$;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.Configuration;
import io.plus.utils.lock.ReadWriteLockMap;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * 一对一  (AsynchronousSocketChannelContext.id <--> AsynchronousSocketChannelContext)<br>
 */
@Slf4j
public class Ids {

    /**
     * key: ChannelContext对象的id字段
     * value: AsynchronousSocketChannelContext
     */
    private ReadWriteLockMap<String, AsynchronousSocketChannelContext> idToChannelContextMap = new ReadWriteLockMap<>(new HashMap<String, AsynchronousSocketChannelContext>());

    public void bind(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        if (asynchronousSocketChannelContext.clientConfiguration.isShortConnection) {
            return;
        }
        try {
            String id = asynchronousSocketChannelContext.getId();
            if ($.isNullOrEmpty(id)) {
                return;
            }
            idToChannelContextMap.put(id, asynchronousSocketChannelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    public AsynchronousSocketChannelContext find(Configuration configuration, String id) {
        if (configuration.isShortConnection) {
            return null;
        }

        if ($.isNullOrEmpty(id)) {
            return null;
        }

        return idToChannelContextMap.get(id);
    }

    public ReadWriteLockMap<String, AsynchronousSocketChannelContext> getIdToChannelContextMap() {
        return idToChannelContextMap;
    }

    public void unbind(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        if (asynchronousSocketChannelContext.clientConfiguration.isShortConnection) {
            return;
        }
        try {
            String id = asynchronousSocketChannelContext.getId();
            if ($.isNullOrEmpty(id)) {
                return;
            }
            idToChannelContextMap.remove(id);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
